/**
 * 242. 有效的字母异位词
 * https://leetcode-cn.com/problems/valid-anagram/
 */
public class Solutions_242 {
    public static void main(String[] args) {
        String s = "anagram", t = "nagaram";  // output:  true
//        String s = "rat", t = "car";  // output:  false

        boolean result = isAnagram(s, t);
        System.out.println(result);
    }

    public static boolean isAnagram(String s, String t) {
        if (s == null && t == null) {
            return true;
        }
        if (s == null || t == null) {
            return false;
        }
        if (s.length() != t.length()) {
            // 长度不同，一定不能为互为异位词
            return false;
        }
        int[] map = new int[26];
        char[] sarr = s.toCharArray();
        char[] tarr = t.toCharArray();

        for (int i = 0; i < s.length(); i++) {
            // 一加一减，若两字符串互为异位词，则最终某字符的个数将为 0
            map[sarr[i] - 'a'] ++;
            map[tarr[i] - 'a'] --;
        }
        for (int i : map) {
            if (i != 0) {
                return false;
            }
        }
        return true;
    }
}
